package com.xiye.system.listener;

import com.xiye.common.entity.*;
import com.xiye.common.session.redis.impl.RedisManager;
import com.xiye.common.util.Const;
import com.xiye.common.util.RightsHelper;
import com.xiye.common.util.Tools;
import com.xiye.system.service.button.ButtonService;
import com.xiye.system.service.buttonrights.ButtonrightsService;
import com.xiye.system.service.menu.MenuService;
import com.xiye.system.service.role.RoleService;
import com.xiye.system.service.user.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Package com.xiye.system.listener
 * @Description 修改权限更新redis缓存权限消息队列
 * @Author 西野
 * @Date 2018-08-28
 * @Version V1.0
 */
@Component
@RabbitListener(queues = Const.RIGHTS_QUEUE)
public class RightsReceiveListener {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RedisManager redisManager;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ButtonService buttonService;
    @Autowired
    private ButtonrightsService buttonrightsService;

    @RabbitHandler
    public void receive(String role_id) throws Exception {
        Role role = roleService.getRoleById(role_id); // 通过role_id获取角色对象
        PageData pd = new PageData();
        pd.put("ROLE_ID", role_id);
        List<PageData> userList = userService.listAllUserByRoldId(pd); // 查出该角色下的所有用户
        if (!userList.isEmpty()) {
            /*循环所有用户更新redis菜单权限*/
            userList.forEach(u -> {
                JSONObject jsonObject = new JSONObject();
                String username = u.getString("USERNAME");
                String user_id = u.getString("USER_ID");
                String key = "menu_user:" + username;
                try {
                    User user = userService.getUserAndRoleById(user_id); // 通过用户ID读取用户信息和角色信息
                    String roleRights = role != null ? role.getRIGHTS() : ""; // 角色权限(菜单权限)
                    String ROLE_IDS = user.getROLE_IDS();
                    jsonObject.put("roleRights", roleRights);
                    List<Menu> allmenuList = new ArrayList<Menu>();
                    allmenuList = this.getAttributeMenu(roleRights, getArrayRoleRights(ROLE_IDS)); // 菜单缓存
                    Map<String, String> getUQX = new HashMap<String, String>();
                    Map<String, List<String>> getUQX2 = new HashMap<String, List<String>>();
                    getUQX = this.getUQX(username);
                    getUQX2 = this.getUQX2(username);
                    jsonObject.put("getUQX", JSONObject.fromObject(getUQX));
                    jsonObject.put("getUQX2", JSONObject.fromObject(getUQX2));
                    jsonObject.put("USER", JSONObject.fromObject(user));
                    jsonObject.put("menuList", JSONArray.fromObject(allmenuList));
                    redisManager.set(key, jsonObject.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    /*
     * @Author 西野
     * @Date 2018-06-22 11:06:06
     * @Description 菜单缓存
     * @Param [session, USERNAME, roleRights, arrayRoleRights]
     * @Return List<Menu>
     */
    public List<Menu> getAttributeMenu(String roleRights, List<String> arrayRoleRights) throws Exception {
        List<Menu> allmenuList = menuService.listAllMenuQx("0"); // 获取所有菜单
        if (Tools.notEmpty(roleRights)) {
            allmenuList = this.readMenu(allmenuList, roleRights, arrayRoleRights); // 根据角色权限获取本权限的菜单列表
        }
        return allmenuList;
    }

    /*
     * @Author 西野
     * @Date 2018-06-22 11:06:06
     * @Description 根据角色权限获取本权限的菜单列表(递归处理)
     * @Param [menuList, roleRights, arrayRoleRights]
     * @Return java.util.List<com.xiye.common.entity.Menu>
     */
    public List<Menu> readMenu(List<Menu> menuList, String roleRights, List<String> arrayRoleRights) {
        menuList.forEach(m -> {
            Boolean b1 = RightsHelper.testRights(roleRights, m.getMENU_ID());
            m.setHasMenu(b1); // 赋予主职角色菜单权限
            if (!b1 && null != arrayRoleRights) {
                arrayRoleRights.forEach(r -> {
                    if (RightsHelper.testRights(r, m.getMENU_ID())) {
                        m.setHasMenu(true);
                        return;
                    }
                });
            }
            if (m.isHasMenu()) { // 判断是否有此菜单权限
                this.readMenu(m.getSubMenu(), roleRights, arrayRoleRights);// 是：继续排查其子菜单
            }
        });
        return menuList;
    }

    /*
     * @Author 西野
     * @Date 2018-06-22 11:06:06
     * @Description 获取副职角色权限List
     * @Param [ROLE_IDS]
     * @Return java.util.List<java.lang.String>
     */
    public List<String> getArrayRoleRights(String ROLE_IDS) {
        if (Tools.notEmpty(ROLE_IDS)) {
            List<String> list = new ArrayList<String>();
            String arryROLE_ID[] = ROLE_IDS.split(",xiye,");
            List<String> rolelist = Arrays.asList(arryROLE_ID);
            rolelist.forEach(r -> {
                try {
                    PageData pd = new PageData();
                    pd.put("ROLE_ID", r);
                    pd = roleService.findObjectById(pd);
                    if (null != pd) {
                        String RIGHTS = pd.getString("RIGHTS");
                        if (Tools.notEmpty(RIGHTS)) {
                            list.add(RIGHTS);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            return list.size() == 0 ? null : list;
        } else {
            return null;
        }
    }

    /*
     * @Author 西野
     * @Date 2018-06-22 12:06:06
     * @Description 获取用户权限
     * @Param [USERNAME]
     * @Return java.util.Map<java.lang.String,java.lang.String>
     */
    public Map<String, String> getUQX(String USERNAME) {
        PageData pd = new PageData();
        Map<String, String> map = new HashMap<String, String>();
        try {
            pd.put(Const.SESSION_USERNAME, USERNAME);
            PageData userpd = userService.findByUsername(pd); // 通过用户名获取用户信息
            String ROLE_ID = userpd.get("ROLE_ID").toString();
            String ROLE_IDS = userpd.getString("ROLE_IDS");
            pd.put("ROLE_ID", ROLE_ID); // 获取角色ID
            pd = roleService.findObjectById(pd); // 获取角色信息
            map.put("adds", pd.getString("ADD_QX")); // 增
            map.put("dels", pd.getString("DEL_QX")); // 删
            map.put("edits", pd.getString("EDIT_QX")); // 改
            map.put("chas", pd.getString("CHA_QX")); // 查
            List<PageData> buttonQXnamelist = new ArrayList<PageData>();
            if ("admin".equals(USERNAME)) {
                buttonQXnamelist = buttonService.listAll(pd); // admin用户拥有所有按钮权限
            } else {
                if (Tools.notEmpty(ROLE_IDS)) {// (主副职角色综合按钮权限)
                    ROLE_IDS = ROLE_IDS + ROLE_ID;
                    String arryROLE_ID[] = ROLE_IDS.split(",xiye,");
                    buttonQXnamelist = buttonrightsService.listAllBrAndQxnameByZF(arryROLE_ID);
                } else { // (主职角色按钮权限)
                    buttonQXnamelist = buttonrightsService.listAllBrAndQxname(pd); // 此角色拥有的按钮权限标识列表
                }
            }
            for (int i = 0; i < buttonQXnamelist.size(); i++) {
                map.put(buttonQXnamelist.get(i).getString("QX_NAME"), "1"); // 按钮权限
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /*
     * @Author 西野
     * @Date 2018-06-22 12:06:06
     * @Description 获取用户权限(处理副职角色)
     * @Param [USERNAME]
     * @Return java.util.Map<java.lang.String,java.util.List<java.lang.String>>
     */
    public Map<String, List<String>> getUQX2(String USERNAME) {
        PageData pd = new PageData();
        Map<String, List<String>> maps = new HashMap<String, List<String>>();
        try {
            pd.put(Const.SESSION_USERNAME, USERNAME);
            PageData userpd = userService.findByUsername(pd); // 通过用户名获取用户信息
            String ROLE_IDS = userpd.getString("ROLE_IDS");
            if (Tools.notEmpty(ROLE_IDS)) {
                String arryROLE_ID[] = ROLE_IDS.split(",xiye,");
                List<String> rolelist = Arrays.asList(arryROLE_ID);
                List<String> addsList = new ArrayList<String>();
                List<String> delsList = new ArrayList<String>();
                List<String> editsList = new ArrayList<String>();
                List<String> chasList = new ArrayList<String>();
                rolelist.forEach(r -> {
                    try {
                        PageData rolePd = new PageData();
                        rolePd.put("ROLE_ID", r);
                        rolePd = roleService.findObjectById(rolePd);
                        addsList.add(rolePd.getString("ADD_QX"));
                        delsList.add(rolePd.getString("DEL_QX"));
                        editsList.add(rolePd.getString("EDIT_QX"));
                        chasList.add(rolePd.getString("CHA_QX"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                maps.put("addsList", addsList); // 增
                maps.put("delsList", delsList); // 删
                maps.put("editsList", editsList); // 改
                maps.put("chasList", chasList); // 查
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maps;
    }
}
